#ifndef SERVER_UI_H_
#define SERVER_UI_H_
#include <gtkmm/button.h>
#include <gtkmm/entry.h>
#include <gtkmm/window.h>
#include <gtkmm/box.h>
#include <gtkmm/togglebutton.h>
#include <iostream>
#include <gtkmm/main.h>

extern log4cpp::Category& category;

class Ui: public Gtk::Window {
public:
	Ui(ServerCfg* m) :
			button("Start server"), exit_button("Exit"), box(true, 50) {
		this->m = m;

		set_border_width(10);
		button.set_size_request(200, 100);

		exit_button.signal_clicked().connect(
				sigc::mem_fun(*this, &Ui::on_exit_clicked));
		button.signal_clicked().connect(
				sigc::mem_fun(*this, &Ui::on_toggle_clicked));
		button.set_active(false);

		add(box);
		box.set_homogeneous(false);
		box.pack_start(button, false, false);
		box.pack_start(exit_button, false, false);
		show_all_children();
	}
protected:
	void on_start_clicked() {
		sock = new Socket;
		//Inicio el thread del servidor
		serv = new Servidor(m, sock);
		serv->start();
		category.notice("Server is running.");
	}

	void on_stop_clicked() {
		try {
			sock->Shutdown(2);
			category.notice("Shutting down server");

		} catch (const ShutdownException& e) {
			//Este catch, por si no habia podido hacer listen, no voy a poder apagar.

		}
		//Espero a que termina el thread del server
		serv->join();
		delete sock;
		delete serv;

		category.notice("Server was stopped");
	}
	void on_exit_clicked() {
		Gtk::Main::quit();
	}
	void on_toggle_clicked() {
		//Si esto da true, quiere decir que el server esta corriendo, lo apago
		if (button.get_active()) {
			on_start_clicked();
			button.set_active(true);
		} else {
			on_stop_clicked();
			button.set_active(false);
		}

	}

private:
	Gtk::VBox box;
	Gtk::Button start_button, stop_button, exit_button;
	Gtk::ToggleButton button;
	Servidor* serv;
	Socket* sock;
	ServerCfg* m;
};

#endif /* SERVER_UI_H_ */
